package com.catersystem.zmy.catersystem.httputils;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;

import com.catersystem.zmy.catersystem.bean.BaseBean;
import com.catersystem.zmy.catersystem.utils.SPUtils;
import com.catersystem.zmy.catersystem.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Map;


/**
 * 网络连接工具类
 */

public class HttpUtils {
    private ProgressDialog mProgressDialog;
    private Context mContext;


    public HttpUtils(Context context, ProgressDialog progressDialog) {
        this.mContext = context;
        this.mProgressDialog = progressDialog;
        showDialog();
    }

    public HttpUtils(Context context, ProgressDialog progressDialog, boolean isShow) {
        this.mContext = context;
        this.mProgressDialog = progressDialog;
        if (isShow) {
            showDialog();
        }
    }

    private void showDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.show();
        }
    }

    /**
     * 异步POST请求
     */
    public void getApi(String url, Map<String, String> data, final IHttpResult httpResult) {

        OkGo.<String>post(url).tag(mContext).params(data).retryCount(3).cacheTime(20000).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    closeDialog();
                    BaseBean baseBean = GsonUtil.GsonToBean(response.body(), BaseBean.class);
                    if (baseBean.getCode() == 0) {
                        httpResult.onSuccess(GsonUtil.GsonString(baseBean.getData()));
                    }
                } catch (JsonSyntaxException e) {
                    ToastUtils.showShortToast(mContext, "数据格式异常");
                    e.printStackTrace();
                } catch (Exception e) {
                    ToastUtils.showShortToast(mContext, "数据错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {
                closeDialog();
            }
        });
    }

    /**
     * 关闭dialog
     */
    private void closeDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    public interface IHttpResult {
        void onSuccess(String result);
    }
}
